package com.yiwei.zxp.activity;

import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.yiwei.zxp.BussinessMainActivity;
import com.yiwei.zxp.R;
import com.yiwei.zxp.api.Api;
import com.yiwei.zxp.api.bean.LoginBean;
import com.yiwei.zxp.api.bean.SmsLoginBean;
import com.yiwei.zxp.api.bean.SmsSendBean;
import com.yiwei.zxp.base.BaseActivity;
import com.yiwei.zxp.constant.UserInfoGlobal;
import com.yiwei.zxp.util.MD5;
import com.yiwei.zxp.util.Network;
import com.yiwei.zxp.util.RxLifeUtil;
import com.yiwei.zxp.util.ToastUtil;
import com.yiwei.zxp.util.UI;
import com.yiwei.zxp.util.Util;
import com.yiwei.zxp.view.V19FrameLayout;

import java.util.LinkedHashSet;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnTextChanged;
import butterknife.Unbinder;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

/**
 * Created by xsooy-pc on 17-12-8.
 */

public class LoginPhoneActivity extends BaseActivity {
    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.txt_right)
    TextView txtRight;
    @BindView(R.id.layout_title)
    V19FrameLayout layoutTitle;
    @BindView(R.id.txt_info)
    TextView txtInfo;
    @BindView(R.id.edit_code)
    EditText editCode;
    @BindView(R.id.btn_clear)
    ImageView btnClear;
    @BindView(R.id.btn_send_code)
    TextView btnSendCode;
    @BindView(R.id.btn_submit)
    TextView btnSubmit;

    private Unbinder unbiner;
    private boolean isSendCode = true;
    private String phone;
    private static final int TIME = 60 * 1000;  //验证码倒计时时间
    private CountDownTimer timer = new CountDownTimer(TIME, 1000) {

        @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
        @Override
        public void onTick(long millisUntilFinished) {
            btnSendCode.setText("重新获取" + (millisUntilFinished / 1000) + "s");
            if (isSendCode) {
                isSendCode = false;
                btnSendCode.setEnabled(false);
                btnSendCode.setBackgroundResource(R.drawable.btn_send_code_uncheck);
                btnSendCode.setTextColor(0xFFFFFFFF);
            }

        }

        @Override
        public void onFinish() {
            isSendCode = true;
            resetBtn();
        }
    };

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void resetBtn() {
        if (timer != null) timer.cancel();
        btnSendCode.setEnabled(true);
        btnSendCode.setText("发送验证码");
        btnSendCode.setTextColor(0xFFFF0030);
        btnSendCode.setBackgroundResource(R.drawable.btn_send_code_check);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_phone);
        initBar();
        unbiner = ButterKnife.bind(this);
        init();
    }

    private void init() {
        phone = getIntent().getStringExtra("phone");
        txtTitle.setText("手机号码登录");
        txtInfo.setText("请输入" + phone + "手机号\n收到的验证码");
        timer.start();
    }


    @OnTextChanged(R.id.edit_code)
    void afterTextChanged1(Editable s) {
        if (TextUtils.isEmpty(UI.toString(editCode))) {
            btnSubmit.setSelected(false);
        } else {
            btnSubmit.setSelected(true);
        }
    }

    public void getSmsSend(String phone) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        loadingDialog.show();
        SmsSendBean bean = new SmsSendBean();
        bean.phone = phone;
        Api.api_service.getForgetSend(bean).compose(RxLifeUtil.loginCheckOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    ToastUtil.makeText(this, "验证码已发送");
                    timer.start();
                });
    }

    public void getSmsLogin(String phone, String code) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        loadingDialog.show();
        SmsLoginBean bean = new SmsLoginBean();
        bean.phone = phone;
        bean.code = code;
        Api.api_service.getSmsLogin(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    if (result.datas.new_user.equals("1")) {
                        Intent intent = new Intent(this, RegisterActivity.class);
                        intent.putExtra("phone", phone);
                        intent.putExtra("verify_token", result.datas.verify_token);
                        startActivity(intent);
                        finish();
                        overridePendingTransition(R.anim.right_enter, R.anim.left_out);

                    } else {
                        Set<String> tagSet = new LinkedHashSet<String>();
                        // tagSet.add(model.getData().getUser_name());
                        tagSet.add(result.datas.mobile);
                        JPushInterface.setAliasAndTags(getApplicationContext(), result.datas.mobile + "", tagSet, new TagAliasCallback() {
                            @Override
                            public void gotResult(int i, String s, Set<String> set) {
                                //  Log.i("", i + s + "       " + set.toString());
//                                ToastUtil.makeText(getApplicationContext(), i+"   "+s+"     "+set.toString(), Toast.LENGTH_SHORT).show();
                                switch (i) {
                                    case 0:
                                        Log.i("", i + s + "       " + set.toString());
                                        // 建议这里往 SharePreference 里写一个成功设置的状态。成功设置一次后，以后不必再次设置了。
                                        break;
                                    case 6002:
                                        Log.i("6002", "60002");
                                        // 延迟 60 秒来调用 Handler 设置别名
                                        break;
                                    default:
                                        Log.i("6002", "default");
                                }
                            }

                        });
                        UserInfoGlobal.saveLoginInfo(result.datas);
                        ToastUtil.makeText(this, "登录成功");
                        Util.startActivity(this, BussinessMainActivity.class);
                        finish();
                    }

                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        unbiner.unbind();
        unbiner = null;
    }

    @OnClick({R.id.btn_back, R.id.btn_clear, R.id.btn_send_code, R.id.btn_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_back:
                finish();
                break;
            case R.id.btn_clear:
                editCode.setText("");
                break;
            case R.id.btn_send_code:
                getSmsSend(phone);
                break;
            case R.id.btn_submit:
                if (TextUtils.isEmpty(UI.toString(editCode))) {
                    ToastUtil.makeText(this, "验证码不能为空");
                    return;
                }
                getSmsLogin(phone, UI.toString(editCode));
                break;
        }
    }
}
